package business.entity;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;

public class CardDBAdapter {
	/**
	 * 把card的值放入contentValues中
	 * @param  要转换的card
	 * @return values 相应的contentValues;
	 */
	public static ContentValues getContentValues(Card card){
		ContentValues values = new ContentValues();
		values.put("name", card.getName());
		values.put("telephone", card.getTelephone());
		values.put("email", card.getEmail());
		values.put("weibo", card.getWeibo());
		values.put("qq", card.getQq());
		return values;
	}
	
	
	/**
	 * @return Card表的建表语句
	 */
	public static String getCreateTableSQL(){
		String cardSQL = "create table card (" +
	            "cardId integer primary key autoincrement, " +
	            "name varchar(50), " +
	            "telephone varhcar(20), " +
	            "email varchar(50), " +
	            "weibo varchar(24), " +
	            "qq varchar(20));";
		return cardSQL;
	}
	

	/**
	 * @return 插入相关的SQL语句，要求要占位符表示其余参数
	 * 并且要写getInsertInstance中产生的instance对应
	 */
	public static String getInsertSQL(){
		return "insert into card (name, telephone, email, weibo, qq) " +
				"values(?,?,?,?,?)";
	}
	
	/**
	 * @param card 要插入的Card
	 * @return 与card的相对的插入参数
	 * 并且要写getInsertSQL中产生的SQL对应
	 */
	public static String[] getInsertInstance(Card card){
		String[] values = new String[]{card.getName(), card.getTelephone(),
				                       card.getEmail(),card.getWeibo(), card.getQq()};
		return values;
	}
	
	/**
	 * @return 与card通过ID查询的SQL
	 */
	public static String getQueryByIdSQL(){
		return "select * from card where cardid=?";
	}
	
	/**
	 * @return 查询所有的语句的SQL
	 */
	public static String getQueryAllSQL(){
		return "select * from card order by name";
	}
	
	/**
	 * 要保证cursor中有记录，并且函数中不会关闭cursor
	 * @param cursor 要保证 
	 * @return 相关的Card对象
	 */
	private static Card convertOneCursor(Cursor cursor){
		Card card = new Card();
		int id = cursor.getInt(cursor.getColumnIndex("cardId"));
		String name = cursor.getString(cursor.getColumnIndex("name"));
		String email = cursor.getString(cursor.getColumnIndex("email"));
		String telephone = cursor.getString(cursor.getColumnIndex("telephone"));
		String qq = cursor.getString(cursor.getColumnIndex("qq"));
		String weibo = cursor.getString(cursor.getColumnIndex("weibo"));
		card.setId(id);
		card.setName(name);
		card.setEmail(email);
		card.setTelephone(telephone);
		card.setQq(qq);
		card.setWeibo(weibo);
		return card;
	}
	
	/**
	 * 从游标cursor中提取相应的Card列表
	 * @param cursor要提取的游标
	 * @return 返回相应的Card列表，注意不会关闭cursor
	 */
	public static List<Card> convertFromCursor(Cursor cursor){
		List<Card> list = new ArrayList<Card>();
		while(cursor.moveToNext()){
			list.add(convertOneCursor(cursor));
		}
		return list;
	}
	
	
	/**
	 * 得到通过名字查询的SQL语句
	 * @return 通过名字查询的SQL语句
	 */
	public static String getQueryByNameSQL(){
		return "select * from card where name like '%' || ? || '%'";
	}
}
